package com.xb.controller;

import com.alibaba.fastjson.JSON;
import com.xb.entity.User;
import com.xb.service.UserService;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Properties;
import java.util.UUID;

@WebServlet("/wx_login")
public class WxLoginController extends HttpServlet {
    private UserService userService=new UserService();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            Properties properties = new Properties();

            properties.load(UserController.class.getClassLoader().getResourceAsStream("config.properties"));

            String appId = properties.getProperty("wx.AppID");
            String appSecret = properties.getProperty("wx.AppSecret");

            String code=req.getParameter("code");

            String url="https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid="+appId +
                    "&secret="+ appSecret+
                    "&code="+ code+
                    "&grant_type=authorization_code";

            HashMap<String,String> access_token_info = execute(url);

            String token = access_token_info.get("access_token");

            String openid = access_token_info.get("openid");

            url = "https://api.weixin.qq.com/sns/userinfo?" +
                    "access_token=" + token +
                    "&openid=" +openid;


            HashMap<String,String>  userInfo = execute(url);

            String userid = userInfo.get("openid");

            User user=   userService.findByOpenId(userid);

            if(user==null){
                //没有该用户
                user=new User();
                // 用户的头像
                user.setPic(userInfo.get("headimgurl"));

                // 性别
                //user.setGender(userInfo.get("sex").toString());
                Object sexObj = userInfo.get("sex");
                if (sexObj != null) {
                    user.setGender(String.valueOf(sexObj));
                } else {
                    // 根据业务需求处理，比如设置为空字符串 "" 或默认值 "未知"
                    user.setGender("");
                }

                // 用户的昵称
                user.setRealName(userInfo.get("nickname").toString());

                // 随机用户名(11位随机字符串)
                user.setUsername(UUID.randomUUID().toString().substring(36 - 15));


                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
               // String format = sdf.format(new Date());

                String format = sdf.format(new Date());
                Date parse = sdf.parse(format);
                user.setRegisterTime (parse);

                user.setLoginTime(parse);

                // 设置微信的openid
                user.setWxOpenid(userInfo.get("openid").toString());

                // 注册一个新的用户
                userService.register(user);

                // 重新查询新的用户
                user = userService.findByOpenId(userInfo.get("openid"));

                HttpSession session = req.getSession();
                session.setAttribute("loginUser",user);

                resp.sendRedirect("/html/home.jsp");

            }else {
                HttpSession session = req.getSession();
                session.setAttribute("loginUser",user);

                resp.sendRedirect("/html/home.jsp");


            }




        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }
    public HashMap execute(String url) throws Exception {

        CloseableHttpClient httpClient = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet(url);

        CloseableHttpResponse response = httpClient.execute(httpGet);

        HttpEntity entity = response.getEntity();
        String utf8 = EntityUtils.toString(entity, "utf8");


        return JSON.parseObject(utf8, HashMap.class);


    }

}
